<template>
  <el-container class="app-container">
    <el-header class="m-t-20">
      <el-button @click="addRoleBtn" type="primary" icon="el-icon-plus">添加角色</el-button>
    </el-header>
    <table-view
      :editBtnMap="true"
      :columns="tableContent"
      :pageList="columnData"
      :editBtnMapList="editBtnMapList"
      @edit-btnclick="editBtnClick"
      :templateDiv="{enable:true}"
    >
      <template slot="enable" slot-scope="scope">
        <el-tag :type="scope.row.enable?'success':'danger'" size="mini" effect="dark">{{ scope.row.enable?'正常':'停用' }}</el-tag>
      </template>
    </table-view>
    <!--分页-->
    <pagination-view  :pagesize="pageInfo.pageSize"
      :currentPage="pageInfo.pageNumber"
      :total="total"
      @size-change="sizeChange"
      @current-change="pageChange"
    ></pagination-view>
    <!--添加角色-->
    <el-dialog :title="showtitle" :visible.sync="addfreightdialog" width="56%" center>
      <el-form ref="form" :model="form" label-width="100px" :rules="formRules" style="width: 60%">
        <el-form-item label="角色名称:" prop="roleName">
          <el-input v-model.trim="form.roleName" placeholder="请输入角色名称" class="rolemanage-input" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色说明：" prop="remark">
          <el-input type="textarea" v-model="form.remark"></el-input>
        </el-form-item>

        <el-form-item label="权限:">
          <el-tree
            class="rolemanage-tree"
            :data="authoritydata"
            show-checkbox
            node-key="menuId"
            ref="tree"
            highlight-pageNum
            :props="defaultProps"
            :default-checked-keys="defaultcheckkeys"
          ></el-tree>
        </el-form-item>

        <el-form-item label="角色状态：" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFreightForm('addFeightForm')">确 定</el-button>
          <el-button @click="resetFreightForm()">取 消</el-button>
        </span>
    </el-dialog>
  </el-container>
</template>

<script>
    import TableView from "@/components/TableView";
    import PaginationView from "@/components/PaginationView";
    import * as roleManage from "@/api/main/account/roleManage";

    export default {
      name: 'roleManage',
      components: {
        PaginationView,
        TableView
      },
      data() {
        return {
          tableContent: [{
            index: 1,
            field: "roleName",
            label: '角色名称',
          }, {
            index: 2,
            field: "remark",
            label: '角色说明',
          },{
            index: 3,
            field: "creatTime",
            label: '创建时间',
          },  {
            index: 3,
            field: "userCount",
            label: '当前人数',
          },  {
            index: 3,
            field: "userCount",
            label: '状态',
          }],
          editBtnMapList: ["update", "delete"], //自定义的按钮内容
          customWidth: "",
          columnData: [],
          total: null,
          pageInfo: {
            pageNum: 1,
            pageSize: 20,
            roleName: '',
          },
          showtitle: "添加角色",
          showType: 'add',
          addfreightdialog: false,
          form: {
            roleName: "",
            hasAllPerm: 1,
            remark: '',
            status:true,
            project:'B'
          },
          role_id: 0,
          formRules: {
            roleName: [{
                required: true,
                message: '请输入角色名称',
                trigger: 'blur'
              },
              {
                min: 1,
                max: 10,
                message: '最多10个字符',
                trigger: 'blur'
              },
            ],
            status:[{required:true}]
          },
          getcheckedkeys: [], //获取勾选的数据
          defaultcheckkeys: [], //默认勾选
          authoritydata: [],
          defaultProps: {
            children: "children",
            label: "name"
          }
        };
      },

      methods: {
        //搜索
        searchList() {
          this.getData()
        },
        //重置搜索
        resetForm() {
          this.pageInfo = {
            pageNum: 1,
            pageSize: 20,
            roleName: '',
          }
          this.getData()
        },
        getData() {
          roleManage.getRoleList(this.pageInfo).then(res => {

            this.columnData = res.body.records
            this.total = Number(res.body.total) || 0
          });
        },
        //获取树状菜单
        getPrivilegeList() {
          roleManage.getPrivilegeList().then(res => {
            this.authoritydata = res.body
          })
        },
        setGridDataFromTree(list, dataSource) {
          if (!(Array.isArray(dataSource) && dataSource.length > 0))
            return;
          dataSource.forEach((father) => {
            list.push(father);
            if (typeof (father.children) == "undefined") {} else {
              this.setGridDataFromTree(list, father.children);
            }
          });
          return list
        },


        createRole(data) {
          roleManage.createRole(data).then(res => {
            this.resetFreightForm();
            this.getData();
          });
        },
        deleteRole(id) {
          let _this = this
          roleManage.deleteRole(id).then(res => {
            _this.getData()
          });
        },
        editBtnClick(val, index, type) {
          let _this = this;
          switch (type) {
            case "update":
              _this.showtitle = "编辑角色";
              _this.showType = 'edit';
              _this.getRoleInfo(val.roleId);
              break;
            case "delete":
              this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                _this.deleteRole(val.roleId);
                _this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              }).catch(() => {
                _this.$message({
                  type: 'info',
                  message: '已取消删除'
                });
              });

              break;
            default:
              break;
          }
        },
        getRoleInfo(id) {
          this.role_id = id
          this.addfreightdialog = true;
          roleManage.getRoleInfo(id).then(res => {
            this.form = res.body
          }).then(() => {
            roleManage.getMenusListByRoleId(id).then(body => {
              var data = body.body
              var newArr = []
              newArr = this.setGridDataFromTree([], data, "").filter(item => item.isIfView == 0)
              newArr.forEach(value => {
                this.$refs.tree.setChecked(value, true, false);
              });
            })
          })
        },
        addRoleBtn() {
          if (this.$refs.tree) {
            this.$refs.tree.setCheckedNodes([])
          }
          this.addfreightdialog = true;
          this.showType = 'add';
          this.showtitle = "添加角色";
        },
        getCheckedKeys(callback) {
          let _getcheckedkeys = []
          let _data = this.$refs.tree.getCheckedKeys()
          _data.map((item, index) => {
            if (item !== undefined) {
              _getcheckedkeys.push(item)
            }
          })
          this.getcheckedkeys = _getcheckedkeys
        },
        submitFreightForm(formName) {
          let _this = this
          _this.$refs.form.validate((valid) => {
            if (valid) {
             /* _this.getCheckedKeys();
              if (_this.getcheckedkeys.length < 1) {
                _this.$message.error('未分配权限！');
                return
              }*/
              let  menuIds = {
                 //menuIds: _this.getcheckedkeys.concat(this.$refs.tree.getHalfCheckedKeys()),
              }
              let _postdata = Object.assign(this.form,menuIds)
              let _type = _this.editclickindex == -1 ? 'add' : 'edit'
              if(this.showType === 'add'){
                _this.createRole(_postdata, _type)
              }else{

              }
            }
          })
        },
        resetFreightForm() {
          this.$refs.form.resetFields();
          this.addfreightdialog = false;
        },
        // pageSize变化函数
        sizeChange(val) {
          this.pageInfo.pageSize = val;
          this.getData();
        },
        // page变化函数
        pageChange(val) {
          this.pageInfo.pageNumber = val;
          this.getData();
        }
      },
      computed: {
        //...mapGetters(["tableContent"])
      },
      created: function () {
        // this.getData();
        // this.getPrivilegeList()
      }
    };
</script>
<style lang="scss">
  .rolemanage {
    padding: 20px;

    .add-more {
      form {
        margin: 0 0 0 10%;

        .rolemanage-tree {
          margin: 10px;
        }
      }

      .rolemanage-input {
        width: 195px;
      }
    }
  }
</style>

